<template>
  <div>
    <h2>一个四位的数字的加上每个位数的数字的和为下面的值：</h2>
    <fieldset>
      <legend>输入求解的值：</legend>
      <input type="number" v-model="countNumber" class="input-number">
      <h4 v-if="notUseable" style="color: red;">输入的值不合理</h4>
    </fieldset>
    <fieldset>
      <legend>算法1</legend>
      <button @click="getResult1">求解</button>
      <h2>结果为：{{result}}</h2>
    </fieldset>
    <fieldset>
      <legend>算法2</legend>
      <button @click="getResult2">求解</button>
      <h2>结果为：{{result2}}</h2>
    </fieldset>
    <h2>出题拿值：</h2>
    <fieldset>
      <legend>请输入任意一个4位数字：</legend>
      <input type="number" v-model="newItem" class="input-number">
      <button @click="getValue">拿值：</button>
      <h2>{{someValue}}</h2>
    </fieldset>
  </div>
</template>

<script>
export default {
  name: "CountNumber",
  data() {
    return {
      countNumber:  '',
      notUseable: false,
      result: '',
      result2: '',

      someValue: ''
    }
  },
  methods: {
    // 计算四位数的逻辑值,算法1
    getResult1(){
      let reg = /^\d{4}$/, value = this.countNumber;
      if(reg.test(value)){
        let canGetResult = true;
        for(let a = 0; a < 10;a++){
          for(let b = 0; b < 10;b++){
            for(let c = 0; c < 10; c++){
              for(let d = 0; d < 10; d++){
                if(a * 1000 + b * 100 + c *10 + d + a + b + c + d == value){
                  this.result = "" + a + b + c + d;
                  canGetResult = false;
                }
              }
            }
          }
        }
        if(canGetResult){
          this.notUseable = true;
        }else{
          this.notUseable = false;
        }
      }else{
        this.notUseable = true
      }
    },
    getResult2(){
      let reg = /^\d{4}$/, value = this.countNumber;
      if(reg.test(value)){
        console.log(value);
        let result = value - 36;
        let canGetResult = true;
        for(result; result <= value; result ++){
          if(result + parseInt(result/1000)%10 + parseInt(result/100)%10 + parseInt(result/10)%10 + result%10 == value){
            this.result2 = result;
            canGetResult = false;
          }
        }
        if(canGetResult){
          this.notUseable = true;
        }else{
          this.notUseable = false;
        }
      }else{
        this.notUseable = true
      }
    },
    getValue(){
      let reg = /^\d{4}$/, value = this.newItem;
      if(reg.test(value)){
        this.someValue = parseInt(value) + parseInt(value/1000)%10 + parseInt(value/100)%10 + parseInt(value/10)%10 + value%10;
      }else{
        return '';
      }
    }
  }
}
</script>

<style>
  .input-number{
    width: 200px;
  }
</style>